import { defineStore } from 'pinia'
import { ref } from 'vue'

// 主题状态管理
export const useThemeStore = defineStore('theme', () => {
  // 主题模式：light或dark
  const theme = ref<'light' | 'dark'>('light')

  // 切换主题
  function toggleTheme() {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
    // 更新文档的data-theme属性
    document.documentElement.setAttribute('data-theme', theme.value)
  }

  // 设置特定主题
  function setTheme(newTheme: 'light' | 'dark') {
    theme.value = newTheme
    document.documentElement.setAttribute('data-theme', theme.value)
  }

  return { theme, toggleTheme, setTheme }
})

// 任务状态类型
export type TaskStatus = 'pending' | 'processing' | 'completed'

// 任务项接口
export interface Task {
  id: string
  extcode: string
  status: TaskStatus
  title?: string
  description?: string
  keywords?: Record<string, string>
  createdAt: string
  updatedAt: string
}

// 任务状态管理
export const useTaskStore = defineStore('task', () => {
  // 所有任务列表
  const tasks = ref<Task[]>([])
  // 加载状态
  const loading = ref(false)
  // 错误信息
  const error = ref<string | null>(null)

  // 获取所有任务
  async function fetchTasks() {
    loading.value = true
    error.value = null
    try {
      // 模拟API调用，实际项目中应替换为真实API
      // const response = await api.getTasks()
      // tasks.value = response.data
      
      // 模拟数据
      setTimeout(() => {
        const mockTasks: Task[] = [
          {
            id: '1',
            extcode: 'C',
            status: 'pending',
            title: '任务1',
            description: '这是一个待处理任务',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          },
          {
            id: '2',
            extcode: 'C',
            status: 'processing',
            title: '任务2',
            description: '这是一个处理中任务',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          },
          {
            id: '3',
            extcode: 'FM',
            status: 'completed',
            title: '任务3',
            description: '这是一个已完成任务',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }
        ]
        tasks.value = mockTasks
        loading.value = false
      }, 500)
    } catch (e) {
      error.value = e instanceof Error ? e.message : '获取任务失败'
      loading.value = false
    }
  }

  // 更新任务状态
  async function updateTaskStatus(taskId: string, newStatus: TaskStatus) {
    const task = tasks.value.find(t => t.id === taskId)
    if (!task) return

    // 乐观更新UI
    const originalStatus = task.status
    task.status = newStatus
    task.updatedAt = new Date().toISOString()

    try {
      // 模拟API调用，实际项目中应替换为真实API
      // await api.updateTaskStatus(taskId, newStatus)
      // 模拟成功
      return true
    } catch (e) {
      // 更新失败，回滚状态
      task.status = originalStatus
      error.value = e instanceof Error ? e.message : '更新任务状态失败'
      return false
    }
  }

  // 按extcode分组统计任务状态
  function getTaskStatsByExtcode() {
    const stats: Record<string, { pending: number, processing: number, completed: number, total: number }> = {}

    tasks.value.forEach(task => {
      if (!stats[task.extcode]) {
        stats[task.extcode] = { pending: 0, processing: 0, completed: 0, total: 0 }
      }
      stats[task.extcode][task.status]++
      stats[task.extcode].total++
    })

    return stats
  }

  return {
    tasks,
    loading,
    error,
    fetchTasks,
    updateTaskStatus,
    getTaskStatsByExtcode
  }
})